package com.shop.cereshop.app.service.wallet.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.cereshop.app.dao.order.CereShopOrderDAO;
import com.shop.cereshop.app.dao.product.CereProductStatsByDayDAO;
import com.shop.cereshop.app.dao.product.CereSkuMemberRealInfoDAO;
import com.shop.cereshop.app.dao.tim.transfer.TransferOrderMapper;
import com.shop.cereshop.app.dao.wallet.BuyerWalletDAO;
import com.shop.cereshop.app.dao.wallet.PayPasswordLogDAO;
import com.shop.cereshop.app.dao.wallet.WalletTransactionDAO;
import com.shop.cereshop.app.domain.wallet.UserIncomeAndExpenseDTO;
import com.shop.cereshop.app.page.cart.CartSku;
import com.shop.cereshop.app.param.wallet.*;
import com.shop.cereshop.app.redis.service.api.StringRedisService;
import com.shop.cereshop.app.service.activity.CereBuyerCouponService;
import com.shop.cereshop.app.service.activity.CerePlatformActivityService;
import com.shop.cereshop.app.service.business.CereBusinessBuyerUserService;
import com.shop.cereshop.app.service.buyer.CereBuyerUserService;
import com.shop.cereshop.app.service.dict.CerePlatformDictService;
import com.shop.cereshop.app.service.discount.CereShopDiscountService;
import com.shop.cereshop.app.service.distributor.CereDistributionOrderService;
import com.shop.cereshop.app.service.groupwork.CereCollageOrderService;
import com.shop.cereshop.app.service.order.CereOrderParentService;
import com.shop.cereshop.app.service.order.CereOrderProductService;
import com.shop.cereshop.app.service.order.CereShopOrderService;
import com.shop.cereshop.app.service.redis.CereRedisKeyServcice;
import com.shop.cereshop.app.service.seckill.CereShopSeckillService;
import com.shop.cereshop.app.service.shop.CereShopConversionService;
import com.shop.cereshop.app.tencent.im.model.redpacket.RedPacket;
import com.shop.cereshop.app.tencent.im.model.transfer.TransferOrder;
import com.shop.cereshop.app.tencent.im.service.RedPacketService;
import com.shop.cereshop.app.service.wallet.BuyerWalletService;
import com.shop.cereshop.commons.constant.*;
import com.shop.cereshop.commons.domain.activity.CereBuyerCoupon;
import com.shop.cereshop.commons.domain.activity.CerePlatformActivity;
import com.shop.cereshop.commons.domain.business.CereBusinessBuyerUser;
import com.shop.cereshop.commons.domain.buyer.CereBuyerUser;
import com.shop.cereshop.commons.domain.collage.CereCollageOrder;
import com.shop.cereshop.commons.domain.dict.CerePlatformDict;
import com.shop.cereshop.commons.domain.distributor.CereDistributionOrder;
import com.shop.cereshop.commons.domain.order.CereOrderParent;
import com.shop.cereshop.commons.domain.order.CereShopOrder;
import com.shop.cereshop.commons.domain.product.CereProductStatsByDay;
import com.shop.cereshop.commons.domain.shop.CereShopConversion;
import com.shop.cereshop.commons.domain.tool.CereShopDiscount;
import com.shop.cereshop.commons.domain.tool.CereShopSeckill;
import com.shop.cereshop.commons.domain.wallet.BuyerWallet;
import com.shop.cereshop.commons.domain.wallet.PayPasswordLog;
import com.shop.cereshop.commons.domain.wallet.WalletTransaction;
import com.shop.cereshop.commons.enums.TransactionTypeEnum;
import com.shop.cereshop.commons.utils.EmptyUtils;
import com.shop.cereshop.commons.utils.PayPasswordUtils;
import com.shop.cereshop.commons.utils.TimeUtils;
import com.shop.cereshop.commons.utils.third.WxCardUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户钱包服务实现类
 *
 * @author wang.yao
 * @date 2025-08-26
 */
@Slf4j
@Service
public class BuyerWalletServiceImpl extends ServiceImpl<BuyerWalletDAO, BuyerWallet> implements BuyerWalletService {

    @Autowired
    private BuyerWalletDAO buyerWalletDAO;

    @Autowired
    private PayPasswordLogDAO payPasswordLogDAO;

    @Autowired
    private WalletTransactionDAO walletTransactionDAO;

    // 订单相关服务
    @Autowired
    private CereOrderParentService cereOrderParentService;

    @Autowired
    private CereShopOrderDAO cereShopOrderDAO;

    @Autowired
    private CereShopConversionService cereShopConversionService;

    @Autowired
    private StringRedisService stringRedisService;

    @Autowired
    private RedissonClient redissonClient;

    // 新增服务注入
    @Autowired
    private CereShopOrderService cereShopOrderService;

    @Autowired
    private CereOrderProductService cereOrderProductService;

    @Autowired
    private CereProductStatsByDayDAO cereProductStatsByDayDAO;

    @Autowired
    private CereSkuMemberRealInfoDAO cereSkuMemberRealInfoDAO;

    @Autowired
    private CereBuyerCouponService cereBuyerCouponService;

    @Autowired
    private CerePlatformActivityService cerePlatformActivityService;

    @Autowired
    private CereBuyerUserService cereBuyerUserService;

    @Autowired
    private CerePlatformDictService cerePlatformDictService;

    @Autowired
    private CereDistributionOrderService cereDistributionOrderService;

    @Autowired
    private CereBusinessBuyerUserService cereBusinessBuyerUserService;

    @Autowired
    private CereCollageOrderService cereCollageOrderService;

    @Autowired
    private CereShopSeckillService cereShopSeckillService;

    @Autowired
    private CereShopDiscountService cereShopDiscountService;

    @Autowired
    private CereRedisKeyServcice cereRedisKeyServcice;

    @Resource
    private RedPacketService redPacketService;

    @Autowired
    private WxCardUtil wxCardUtil;

    @Resource
    private TransferOrderMapper transferOrderMapper;

    @Override
    public WalletInfoVO getWalletInfo(Long buyerUserId) {
        // 获取或创建钱包
        BuyerWallet wallet = getOrCreateWallet(buyerUserId);

        // 转换为VO
        WalletInfoVO walletInfoVO = new WalletInfoVO();
        walletInfoVO.setWalletId(wallet.getWalletId());
        walletInfoVO.setBuyerUserId(wallet.getBuyerUserId());
        walletInfoVO.setBalance(wallet.getBalance());

        // 设置支付密码相关信息
        walletInfoVO.setIsSetPayPassword(wallet.getIsSetPayPassword());
        walletInfoVO.setPayPasswordErrorCount(wallet.getPayPasswordErrorCount());
        walletInfoVO.setPayPasswordLockTime(wallet.getPayPasswordLockTime());

        // 计算剩余锁定时间
        if (PayPasswordUtils.isPayPasswordLocked(wallet.getPayPasswordErrorCount(), wallet.getPayPasswordLockTime())) {
            long remainingTime = PayPasswordUtils.getRemainingLockTime(wallet.getPayPasswordLockTime());
            walletInfoVO.setRemainingLockTime(remainingTime);
        } else {
            walletInfoVO.setRemainingLockTime(0L);
        }

        return walletInfoVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WalletInitResult initWallet(Long buyerUserId) {
        // 检查是否已存在钱包
        BuyerWallet existingWallet = buyerWalletDAO.selectByUserId(buyerUserId);
        if (existingWallet != null) {
            log.info("用户{}钱包已存在，无需初始化", buyerUserId);
            return WalletInitResult.existingWallet(existingWallet);
        }

        // 创建新钱包
        BuyerWallet wallet = new BuyerWallet();
        wallet.setBuyerUserId(buyerUserId);
        wallet.setBalance(BigDecimal.ZERO);
        wallet.setFrozenBalance(BigDecimal.ZERO); // 数据库字段，保持为0
        wallet.setIsSetPayPassword(false);
        wallet.setPayPasswordErrorCount(0);
        wallet.setCreateTime(TimeUtils.yyMMddHHmmss());
        wallet.setUpdateTime(TimeUtils.yyMMddHHmmss());

        // 保存钱包
        buyerWalletDAO.insert(wallet);

        log.info("用户{}钱包初始化成功", buyerUserId);
        return WalletInitResult.newWallet(wallet);
    }

    @Override
    public BuyerWallet getOrCreateWallet(Long buyerUserId) {
        // 先查询现有钱包
        BuyerWallet wallet = buyerWalletDAO.selectByUserId(buyerUserId);

        // 如果不存在则创建
        if (wallet == null) {
            WalletInitResult result = initWallet(buyerUserId);
            wallet = result.getWallet();
        }

        return wallet;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WalletConstant.PayPasswordSetResult setPayPassword(Long buyerUserId, String payPassword, String ipAddress) {
        try {
            // 获取钱包
            BuyerWallet wallet = getOrCreateWallet(buyerUserId);

            // 检查是否已设置支付密码
            if (wallet.getIsSetPayPassword()) {
                log.warn("用户{}已设置支付密码", buyerUserId);
                return WalletConstant.PayPasswordSetResult.ALREADY_SET;
            }

            // 加密支付密码
            String encryptedPassword = PayPasswordUtils.encryptPayPassword(payPassword);

            // 更新支付密码
            String updateTime = TimeUtils.yyMMddHHmmss();
            int result = buyerWalletDAO.updatePayPassword(buyerUserId, encryptedPassword, true, updateTime);

            if (result > 0) {
                // 记录操作日志
                recordPayPasswordLog(buyerUserId, WalletConstant.PayPasswordOperationType.SET, true, ipAddress);
                log.info("用户{}设置支付密码成功", buyerUserId);
                return WalletConstant.PayPasswordSetResult.SUCCESS;
            }

            return WalletConstant.PayPasswordSetResult.FAILED;
        } catch (Exception e) {
            log.error("用户{}设置支付密码失败", buyerUserId, e);
            return WalletConstant.PayPasswordSetResult.FAILED;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WalletConstant.PayPasswordModifyResult modifyPayPassword(Long buyerUserId, String oldPassword, String newPassword, String ipAddress) {
        try {
            // 获取钱包
            BuyerWallet wallet = getOrCreateWallet(buyerUserId);

            // 检查是否已设置支付密码
            if (!wallet.getIsSetPayPassword()) {
                log.warn("用户{}未设置支付密码", buyerUserId);
                return WalletConstant.PayPasswordModifyResult.NOT_SET;
            }

            // 验证旧密码
            if (!PayPasswordUtils.verifyPayPassword(oldPassword, wallet.getPayPassword())) {
                // 记录验证失败日志
                recordPayPasswordLog(buyerUserId, WalletConstant.PayPasswordOperationType.MODIFY, false, ipAddress);
                log.warn("用户{}修改支付密码失败：旧密码错误", buyerUserId);
                return WalletConstant.PayPasswordModifyResult.OLD_PASSWORD_ERROR;
            }

            // 加密新密码
            String encryptedNewPassword = PayPasswordUtils.encryptPayPassword(newPassword);

            // 更新支付密码
            String updateTime = TimeUtils.yyMMddHHmmss();
            int result = buyerWalletDAO.updatePayPassword(buyerUserId, encryptedNewPassword, true, updateTime);

            if (result > 0) {
                // 记录操作日志
                recordPayPasswordLog(buyerUserId, WalletConstant.PayPasswordOperationType.MODIFY, true, ipAddress);
                log.info("用户{}修改支付密码成功", buyerUserId);
                return WalletConstant.PayPasswordModifyResult.SUCCESS;
            }

            return WalletConstant.PayPasswordModifyResult.FAILED;
        } catch (Exception e) {
            log.error("用户{}修改支付密码失败", buyerUserId, e);
            return WalletConstant.PayPasswordModifyResult.FAILED;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean verifyPayPassword(Long buyerUserId, String payPassword, String ipAddress) {
        try {
            // 获取钱包
            BuyerWallet wallet = getOrCreateWallet(buyerUserId);

            // 检查是否已设置支付密码
            if (!wallet.getIsSetPayPassword()) {
                log.warn("用户{}未设置支付密码", buyerUserId);
                return false;
            }

            // 检查支付密码是否被锁定
            if (PayPasswordUtils.isPayPasswordLocked(wallet.getPayPasswordErrorCount(), wallet.getPayPasswordLockTime())) {
                log.warn("用户{}支付密码被锁定", buyerUserId);
                return false;
            }

            // 验证支付密码
            boolean isValid = PayPasswordUtils.verifyPayPassword(payPassword, wallet.getPayPassword());

            if (isValid) {
                // 验证成功，重置错误次数
                String updateTime = TimeUtils.yyMMddHHmmss();
                buyerWalletDAO.resetPayPasswordErrorInfo(buyerUserId, updateTime);

                // 记录验证成功日志
                recordPayPasswordLog(buyerUserId, WalletConstant.PayPasswordOperationType.VERIFY, true, ipAddress);
                log.info("用户{}支付密码验证成功", buyerUserId);
                return true;
            } else {
                // 验证失败，增加错误次数
                int newErrorCount = wallet.getPayPasswordErrorCount() + 1;
                String lockTime = null;

                // 如果错误次数达到上限，设置锁定时间
                if (newErrorCount >= WalletConstant.PayPasswordConfig.MAX_ERROR_COUNT) {
                    lockTime = TimeUtils.yyMMddHHmmss();
                }

                String updateTime = TimeUtils.yyMMddHHmmss();
                buyerWalletDAO.updatePayPasswordErrorInfo(buyerUserId, newErrorCount, lockTime, updateTime);

                // 记录验证失败日志
                recordPayPasswordLog(buyerUserId, WalletConstant.PayPasswordOperationType.VERIFY, false, ipAddress);
                log.warn("用户{}支付密码验证失败，错误次数：{}", buyerUserId, newErrorCount);
                return false;
            }
        } catch (Exception e) {
            log.error("用户{}支付密码验证异常", buyerUserId, e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean resetPayPassword(Long buyerUserId, String smsCode, String newPassword, String ipAddress) {
        try {
            // TODO: 验证短信验证码
            // 这里需要集成短信验证服务

            // 获取钱包
            BuyerWallet wallet = getOrCreateWallet(buyerUserId);

            // 加密新密码
            String encryptedNewPassword = PayPasswordUtils.encryptPayPassword(newPassword);

            // 更新支付密码
            String updateTime = TimeUtils.yyMMddHHmmss();
            int result = buyerWalletDAO.updatePayPassword(buyerUserId, encryptedNewPassword, true, updateTime);

            if (result > 0) {
                // 重置错误信息
                buyerWalletDAO.resetPayPasswordErrorInfo(buyerUserId, updateTime);

                // 记录操作日志
                recordPayPasswordLog(buyerUserId, WalletConstant.PayPasswordOperationType.RESET, true, ipAddress);
                log.info("用户{}重置支付密码成功", buyerUserId);
                return true;
            }

            return false;
        } catch (Exception e) {
            log.error("用户{}重置支付密码失败", buyerUserId, e);
            return false;
        }
    }

    @Override
    public boolean isPayPasswordLocked(Long buyerUserId) {
        try {
            BuyerWallet wallet = getOrCreateWallet(buyerUserId);
            return PayPasswordUtils.isPayPasswordLocked(wallet.getPayPasswordErrorCount(), wallet.getPayPasswordLockTime());
        } catch (Exception e) {
            log.error("检查用户{}支付密码锁定状态失败", buyerUserId, e);
            return false;
        }
    }

    @Override
    public long getRemainingLockTime(Long buyerUserId) {
        try {
            BuyerWallet wallet = getOrCreateWallet(buyerUserId);
            return PayPasswordUtils.getRemainingLockTime(wallet.getPayPasswordLockTime());
        } catch (Exception e) {
            log.error("获取用户{}剩余锁定时间失败", buyerUserId, e);
            return 0;
        }
    }

    /**
     * 记录支付密码操作日志
     *
     * @param buyerUserId     用户ID
     * @param operationType   操作类型
     * @param operationResult 操作结果
     * @param ipAddress       IP地址
     */
    private void recordPayPasswordLog(Long buyerUserId, Integer operationType, boolean operationResult, String ipAddress) {
        try {
            PayPasswordLog log = new PayPasswordLog();
            log.setBuyerUserId(buyerUserId);
            log.setOperationType(operationType);
            log.setOperationResult(operationResult ? 1 : 0);
            log.setIpAddress(ipAddress);
            log.setCreateTime(TimeUtils.yyMMddHHmmss());

            payPasswordLogDAO.insert(log);
        } catch (Exception e) {
            log.error("记录支付密码操作日志失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBalance(Long buyerUserId, BigDecimal amount, Integer transactionType, String orderId, String description) {
        try {
            // 获取钱包
            BuyerWallet wallet = getOrCreateWallet(buyerUserId);

            // 计算新余额
            BigDecimal newBalance = wallet.getBalance().add(amount);

            // 检查余额是否足够（消费时）
            if (amount.compareTo(BigDecimal.ZERO) < 0 && newBalance.compareTo(BigDecimal.ZERO) < 0) {
                log.warn("用户{}余额不足，当前余额：{}，消费金额：{}", buyerUserId, wallet.getBalance(), amount);
                return false;
            }

            // 更新钱包余额
            String updateTime = TimeUtils.yyMMddHHmmss();
            int result = buyerWalletDAO.updateBalance(buyerUserId, newBalance, updateTime);

            if (result > 0) {
                // TODO: 记录交易流水
                // 这里需要实现交易流水记录功能
                log.info("用户{}余额更新成功，变动金额：{}，新余额：{}", buyerUserId, amount, newBalance);
                return true;
            }

            return false;
        } catch (Exception e) {
            log.error("更新用户{}余额失败", buyerUserId, e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean consume(Long buyerUserId, BigDecimal amount, Integer consumeType, String description, String orderNo, String payPassword, String ipAddress) {
        try {
            // 1. 获取钱包信息
            BuyerWallet wallet = getOrCreateWallet(buyerUserId);
            TransactionTypeEnum transactionType = TransactionTypeEnum.getByCode(consumeType);
            if (null == transactionType) {
                log.error("用户{}消费失败：消费类型错误", buyerUserId);
                return false;
            }
            //获取订单信息金额
            Double orderAmount = findOrderAmount(transactionType.getCode(), orderNo, buyerUserId);
            if (orderAmount == null) {
                log.error("用户{}消费失败：订单信息错误", buyerUserId);
                return false;
            }
            //将orderAmount赋值给amount
            amount = BigDecimal.valueOf(orderAmount);
            // 2. 验证支付密码
            if (wallet.getIsSetPayPassword()) {
                if (payPassword == null || payPassword.isEmpty()) {
                    log.error("用户{}消费失败：支付密码不能为空", buyerUserId);
                    return false;
                }

                boolean passwordValid = verifyPayPassword(buyerUserId, payPassword, ipAddress);
                if (!passwordValid) {
                    log.error("用户{}消费失败：支付密码验证失败", buyerUserId);
                    return false;
                }
            }
            // 3. 检查余额是否充足
            if (wallet.getBalance().compareTo(amount) < 0) {
                log.error("用户{}消费失败：余额不足，当前余额：{}，消费金额：{}", buyerUserId, wallet.getBalance(), amount);
                return false;
            }

            // 4. 扣减余额
            String updateTime = TimeUtils.yyMMddHHmmss();
            int updateRows = buyerWalletDAO.deductBalance(buyerUserId, amount, updateTime);
            if (updateRows == 0) {
                log.error("用户{}消费失败：余额扣减失败", buyerUserId);
                return false;
            }

            // 5. 记录交易流水
            WalletTransaction transaction = new WalletTransaction();
            transaction.setBuyerUserId(buyerUserId);
            transaction.setTransactionType(consumeType); // 2-消费
            transaction.setAmount(amount);
            transaction.setBalanceBefore(wallet.getBalance());
            transaction.setBalanceAfter(wallet.getBalance().subtract(amount));
            transaction.setDescription(transactionType.getMsg());
            transaction.setOrderId(orderNo);
            transaction.setCreateTime(updateTime);

            walletTransactionDAO.insert(transaction);

            log.info("用户{}消费成功，金额：{}，类型：{}", buyerUserId, amount, consumeType);
            return true;

        } catch (Exception e) {
            log.error("用户{}消费失败", buyerUserId, e);
            return false;
        }
    }

    @Override
    public List<WalletTransactionVO> getTransactionList(Long buyerUserId, WalletTransactionQueryVO queryVO) {
        try {
            // 计算分页参数
            int offset = (queryVO.getPage() - 1) * queryVO.getSize();

            // 查询流水列表
            List<WalletTransaction> transactions = walletTransactionDAO.selectTransactionList(
                    buyerUserId,
                    queryVO.getTransactionType(),
                    queryVO.getStartDate(),
                    queryVO.getEndDate(),
                    queryVO.getMinAmount() != null ? new BigDecimal(queryVO.getMinAmount()) : null,
                    queryVO.getMaxAmount() != null ? new BigDecimal(queryVO.getMaxAmount()) : null,
                    offset,
                    queryVO.getSize()
            );

            // 转换为VO
            return transactions.stream().map(this::convertToTransactionVO).collect(java.util.stream.Collectors.toList());

        } catch (Exception e) {
            log.error("查询用户{}钱包流水失败", buyerUserId, e);
            return new java.util.ArrayList<>();
        }
    }

    @Override
    public UserIncomeAndExpenseDTO getUserIncomeAndExpense(Long buyerUserId, String startDate, String endDate) {
        return walletTransactionDAO.getUserIncomeAndExpense(buyerUserId, startDate, endDate);
    }

    @Override
    public WalletTransactionVO getTransactionDetail(Long transactionId) {
        try {
            WalletTransaction transaction = walletTransactionDAO.selectTransactionById(transactionId);
            if (transaction == null) {
                return null;
            }

            return convertToTransactionVO(transaction);

        } catch (Exception e) {
            log.error("查询钱包流水详情失败，流水ID：{}", transactionId, e);
            return null;
        }
    }

    /**
     * 将WalletTransaction转换为WalletTransactionVO
     */
    private WalletTransactionVO convertToTransactionVO(WalletTransaction transaction) {
        WalletTransactionVO vo = new WalletTransactionVO();
        vo.setTransactionId(transaction.getTransactionId());
        vo.setBuyerUserId(transaction.getBuyerUserId());
        vo.setIncomeOrExpense(getIncomeOrExpense(transaction.getTransactionType()));
//        vo.setTransactionType(getTransactionTypeDesc(transaction.getTransactionType()));
        vo.setTransactionType(TransactionTypeEnum.getMsgByCode(transaction.getTransactionType()));
        vo.setAmount(transaction.getAmount());
        vo.setBeforeBalance(transaction.getBalanceBefore());
        vo.setAfterBalance(transaction.getBalanceAfter());
        vo.setDescription(transaction.getDescription());
        vo.setOrderNo(transaction.getOrderId());
        // 默认成功状态
        vo.setStatus("SUCCESS");
        // 时间转换：String -> LocalDateTime
        if (transaction.getCreateTime() != null) {
            try {
                // 尝试解析完整的时间格式
                vo.setCreateTime(java.time.LocalDateTime.parse(transaction.getCreateTime(),
                        java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                vo.setUpdateTime(java.time.LocalDateTime.parse(transaction.getCreateTime(),
                        java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            } catch (Exception e1) {
                try {
                    // 尝试解析日期格式
                    java.time.LocalDate date = java.time.LocalDate.parse(transaction.getCreateTime());
                    vo.setCreateTime(date.atStartOfDay());
                    vo.setUpdateTime(date.atStartOfDay());
                } catch (Exception e2) {
                    vo.setCreateTime(java.time.LocalDateTime.now());
                    vo.setUpdateTime(java.time.LocalDateTime.now());
                }
            }
        } else {
            vo.setCreateTime(java.time.LocalDateTime.now());
            vo.setUpdateTime(java.time.LocalDateTime.now());
        }
        return vo;
    }

    /**
     * 根据交易类型 获取收支类型（1-收入 2-支出）
     * @param transactionType 交易类型 1-充值 2-消费 3-退款 4-提现 5-发红包付款 6-领取红包收款 7-红包退款 8-转账付款 9-领取转账收款 10-转账退款
     */
    private Integer getIncomeOrExpense(Integer transactionType){
        if (transactionType == null) {
            log.error("交易类型为空");
            return 0;
        }
        // 收入 1-充值 3-退款 6-领取红包收款 7-红包退款 9-领取转账收款 10-转账退款
        boolean isIncome = TransactionTypeEnum.RECHARGE.getCode().equals(transactionType)
                || TransactionTypeEnum.REFUND.getCode().equals(transactionType)
                || TransactionTypeEnum.RED_PACKET_RECEIVE.getCode().equals(transactionType)
                || TransactionTypeEnum.TRANSFER_ORDER_RECEIVE.getCode().equals(transactionType)
                || TransactionTypeEnum.RED_PACKET_REFUND.getCode().equals(transactionType)
                || TransactionTypeEnum.TRANSFER_ORDER_REFUND.getCode().equals(transactionType);

        // 支出 2-消费 4-提现 5-发红包付款 8-转账付款
        boolean isExpense = TransactionTypeEnum.CONSUME.getCode().equals(transactionType)
                || TransactionTypeEnum.WITHDRAW.getCode().equals(transactionType)
                || TransactionTypeEnum.RED_PACKET_PAY.getCode().equals(transactionType)
                || TransactionTypeEnum.TRANSFER_ORDER_PAY.getCode().equals(transactionType);
        if (isIncome) {
            return 1;
        } else if (isExpense) {
            return 2;
        } else {
            log.error("交易类型错误：{}", transactionType);
            return 0;
        }
    }

    /**
     * 获取交易类型描述
     */
    private String getTransactionTypeDesc(Integer transactionType) {
        if (transactionType == null) {
            return "未知";
        }
        switch (transactionType) {
            case 1:
                return "充值";
            case 2:
                return "消费";
            case 3:
                return "退款";
            case 4:
                return "提现";
            default:
                return "未知";
        }
    }

    @Override
    public WalletPayCheckResult checkWalletBalanceForPay(Long buyerUserId, Long orderId, Integer orderType, Long collageId) {
        try {
            // 1. 拼团检查 - 如果是拼团订单，检查剩余拼团人数
            if (!EmptyUtils.isLongEmpty(collageId)) {
                //定义加锁key
                String key = "拼团订单" + collageId;
                //加锁
                RLock redissonLock = redissonClient.getLock(key);
                redissonLock.lock();
                Object obj = stringRedisService.get(String.valueOf(collageId));
                if (!EmptyUtils.isEmpty(obj)) {
                    int number = (int) stringRedisService.get(String.valueOf(collageId));
                    if (number <= 0) {
                        //如果剩余拼团人数小于等于0,拼单已成团,无法支付了
                        redissonLock.unlock();
                        return WalletPayCheckResult.failure("拼单已成团,无法支付了", CoReturnFormat.WALLET_BALANCE_INSUFFICIENT);
                    }
                }
                //解锁
                redissonLock.unlock();
            }

            // 2. 获取订单信息（按照gotoAppPay的逻辑）
            List<Long> shopIds = null;
            String orderFormId = "";
            BigDecimal price = null;

            if (ParamEnum.ORDER_TYPE_PARENT.getCode().equals(orderType)) {
                // 父订单提交,查询父订单编号
                CereOrderParent parent = cereOrderParentService.findById(orderId);
                if (parent == null) {
                    return WalletPayCheckResult.failure("父订单不存在", CoReturnFormat.WALLET_BALANCE_INSUFFICIENT);
                }
                orderFormId = parent.getParentFormid();
                price = parent.getPrice();
                // 根据父订单查询该订单下所有的店铺id
                shopIds = cereOrderParentService.findShopIds(orderId);
            } else {
                // 子订单提交,查询子订单编号
                CereShopOrder order = cereShopOrderDAO.findById(orderId);
                if (order == null) {
                    return WalletPayCheckResult.failure("子订单不存在", CoReturnFormat.WALLET_BALANCE_INSUFFICIENT);
                }
                orderFormId = order.getOrderFormid();
                price = order.getPrice();
                // 根据子订单查询该订单店铺id
                shopIds = cereShopOrderDAO.findShopId(orderId);
            }

            // 3. 获取用户钱包
            BuyerWallet wallet = getOrCreateWallet(buyerUserId);

            // 4. 检查余额是否足够
            if (wallet.getBalance().compareTo(price) < 0) {
                return WalletPayCheckResult.failure(
                        String.format("钱包余额不足，当前余额：%.2f，需要支付：%.2f", wallet.getBalance(), price),
                        CoReturnFormat.WALLET_BALANCE_INSUFFICIENT
                );
            }

            // 5. 记录转化数据（按照gotoAppPay的逻辑）
            if (!EmptyUtils.isEmpty(shopIds)) {
                List<CereShopConversion> conversions = new ArrayList<>();
                shopIds.forEach(id -> {
                    // 新增转化数据
                    CereShopConversion cereShopConversion = new CereShopConversion();
                    cereShopConversion.setShopId(id);
                    cereShopConversion.setCreateTime(TimeUtils.yyMMddHHmmss());
                    cereShopConversion.setType(ParamEnum.CONVERSION_PAY.getCode());
                    conversions.add(cereShopConversion);
                });
                // 批量插入转化数据
                cereShopConversionService.insertBatch(conversions);
            }

            return WalletPayCheckResult.success(
                    "钱包余额充足，可以支付",
                    price.toString(),
                    wallet.getBalance().toString()
            );

        } catch (Exception e) {
            log.error("检查钱包余额失败，用户ID：{}，订单ID：{}", buyerUserId, orderId, e);
            return WalletPayCheckResult.failure("检查余额失败，请稍后重试", CoReturnFormat.WALLET_BALANCE_INSUFFICIENT);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WalletPayExecuteResult executeWalletPay(Long buyerUserId, Long orderId, Integer orderType, Long collageId, String payPassword, String ipAddress) {
        try {
            // 1. 拼团检查 - 如果是拼团订单，检查剩余拼团人数
            if (!EmptyUtils.isLongEmpty(collageId)) {
                //定义加锁key
                String key = "拼团订单" + collageId;
                //加锁
                RLock redissonLock = redissonClient.getLock(key);
                redissonLock.lock();
                Object obj = stringRedisService.get(String.valueOf(collageId));
                if (!EmptyUtils.isEmpty(obj)) {
                    int number = (int) stringRedisService.get(String.valueOf(collageId));
                    if (number <= 0) {
                        //如果剩余拼团人数小于等于0,拼单已成团,无法支付了
                        redissonLock.unlock();
                        return WalletPayExecuteResult.failure("拼单已成团,无法支付了", CoReturnFormat.WALLET_PAY_FAIL);
                    }
                }
                //解锁
                redissonLock.unlock();
            }

            // 2. 验证支付密码
            if (!verifyPayPassword(buyerUserId, payPassword, ipAddress)) {
                return WalletPayExecuteResult.failure("支付密码错误", CoReturnFormat.WALLET_PAY_PASSWORD_ERROR);
            }

            // 2. 获取订单信息（按照gotoAppPay的逻辑）
            List<Long> shopIds = null;
            String orderFormId = "";
            BigDecimal price = null;

            if (ParamEnum.ORDER_TYPE_PARENT.getCode().equals(orderType)) {
                // 父订单提交,查询父订单编号
                CereOrderParent parent = cereOrderParentService.findById(orderId);
                if (parent == null) {
                    return WalletPayExecuteResult.failure("父订单不存在", CoReturnFormat.WALLET_PAY_FAIL);
                }
                orderFormId = parent.getParentFormid();
                price = parent.getPrice();
                // 根据父订单查询该订单下所有的店铺id
                shopIds = cereOrderParentService.findShopIds(orderId);
            } else {
                // 子订单提交,查询子订单编号
                CereShopOrder order = cereShopOrderDAO.findById(orderId);
                if (order == null) {
                    return WalletPayExecuteResult.failure("子订单不存在", CoReturnFormat.WALLET_PAY_FAIL);
                }
                if (!Objects.equals(order.getState(), IntegerEnum.ORDER_STAY_PAY.getCode())) {
                    return WalletPayExecuteResult.failure(CoReturnFormat.messageMap.get(CoReturnFormat.ORDER_NOT_TAKE), CoReturnFormat.ORDER_NOT_TAKE);
                }
                orderFormId = order.getOrderFormid();
                price = order.getPrice();
                // 根据子订单查询该订单店铺id
                shopIds = cereShopOrderDAO.findShopId(orderId);
            }

            // 3. 执行钱包消费
            boolean success = consume(buyerUserId, price, TransactionTypeEnum.CONSUME.getCode(), "订单支付：" + orderFormId, orderFormId, payPassword, ipAddress);

            if (success) {
                // 4. 支付成功，调用后续处理逻辑（相当于微信支付的回调）
                String transactionId = "WALLET" + orderFormId + System.currentTimeMillis();
                handleWalletPaySuccess(orderFormId, transactionId, orderFormId);
                return WalletPayExecuteResult.success("支付成功", transactionId, orderFormId);
            } else {
                return WalletPayExecuteResult.failure("支付失败，请稍后重试", CoReturnFormat.WALLET_PAY_FAIL);
            }

        } catch (Exception e) {
            log.error("钱包支付执行失败，用户ID：{}，订单ID：{}", buyerUserId, orderId, e);
            return WalletPayExecuteResult.failure("支付失败，请稍后重试", CoReturnFormat.WALLET_PAY_FAIL);
        }
    }


    /**
     * 处理钱包支付成功后的逻辑（相当于微信支付的回调）
     * 实现handleWxLog方法的全部业务逻辑
     */
    private void handleWalletPaySuccess(String orderFormId, String transactionId, String orderNo) {
        try {
            log.info("开始处理钱包支付成功逻辑，订单编号：{}，交易ID：{}", orderFormId, transactionId);

            // 1. 支付有礼处理
            try {
                cereShopOrderService.payGift(orderFormId);
                log.info("支付有礼处理完成，订单编号：{}", orderFormId);
            } catch (Exception e) {
                log.warn("支付有礼处理失败，订单编号：{}，错误：{}", orderFormId, e.getMessage());
            }

            // 2. 核心业务逻辑处理 - 实现handleWxLog的全部逻辑
            String time = TimeUtils.yyMMddHHmmss();
            List<CereShopOrder> list = null;

            // 查询是否为父订单编号
            CereOrderParent parent = cereShopOrderDAO.findByParentFormid(orderFormId);
            if (parent != null) {
                // 查询所有子订单数据
                list = cereShopOrderDAO.findByParentId(parent.getParentId());
                log.info("查询到父订单，子订单数量：{}", list != null ? list.size() : 0);
            } else {
                // 子订单支付回调
                list = cereShopOrderDAO.findByFormid(orderFormId);
                log.info("查询到子订单，订单数量：{}", list != null ? list.size() : 0);
            }

            // 支付业务处理
            if (!EmptyUtils.isEmpty(list)) {
                List<CereDistributionOrder> distributionOrders = new ArrayList<>();
                List<CereShopConversion> conversions = new ArrayList<>();
                BigDecimal total = BigDecimal.ZERO;
                Long platformCouponId = null;
                List<Long> orderIdList = new ArrayList<>();

                for (CereShopOrder order : list) {
                    total = total.add(order.getPrice());
                    orderIdList.add(order.getOrderId());

                    // 根据订单类型处理不同活动
                    if (!EmptyUtils.isEmpty(order.getShopGroupWorkId())) {
                        // 拼单支付业务处理
                        handleGroupWork(order, transactionId, orderNo, time);
                        log.info("拼团订单处理完成，订单ID：{}", order.getOrderId());
                    } else if (!EmptyUtils.isEmpty(order.getShopSeckillId())) {
                        // 秒杀活动支付业务处理
                        handleSeckill(order, transactionId, orderNo, time);
                        log.info("秒杀订单处理完成，订单ID：{}", order.getOrderId());
                    } else if (!EmptyUtils.isEmpty(order.getShopDiscountId())) {
                        // 限时折扣活动支付业务处理
                        handleDiscount(order, transactionId, orderNo, time);
                        log.info("限时折扣订单处理完成，订单ID：{}", order.getOrderId());
                    } else {
                        // 正常下单业务处理
                        handleOrder(order, transactionId, orderNo, time, distributionOrders, conversions);
                        log.info("普通订单处理完成，订单ID：{}", order.getOrderId());
                    }

                    // 更新用户最后购买时间
                    CereBusinessBuyerUser bbu = new CereBusinessBuyerUser();
                    bbu.setShopId(order.getShopId());
                    bbu.setBuyerUserId(order.getBuyerUserId());
                    bbu.setUpdateTime(time);
                    cereBusinessBuyerUserService.refreshUpdateTime(bbu);

                    // 记录优惠券ID
                    if (order.getCouponId() != null) {
                        platformCouponId = order.getCouponId();
                    }
                }

                // 更新商品销量统计
                updateProductSalesStats(orderIdList);

                // 处理优惠券核销
                if (platformCouponId != null) {
                    handleCouponWriteOff(platformCouponId, list.get(0).getBuyerUserId());
                }

                // 增加用户成长值和积分
                updateUserGrowthAndCredit(list.get(0).getBuyerUserId(), total);

                // 批量插入分销订单数据
                if (!EmptyUtils.isEmpty(distributionOrders)) {
                    cereDistributionOrderService.insertBatch(distributionOrders);
                    log.info("分销订单数据插入完成，数量：{}", distributionOrders.size());
                }

                // 批量插入转化数据
                if (!EmptyUtils.isEmpty(conversions)) {
                    cereShopConversionService.insertBatch(conversions);
                    log.info("转化数据插入完成，数量：{}", conversions.size());
                }

                log.info("钱包支付成功逻辑处理完成，订单编号：{}，总金额：{}", orderFormId, total);
            } else {
                log.warn("未找到相关订单数据，订单编号：{}", orderFormId);
            }

        } catch (Exception e) {
            log.error("处理钱包支付成功逻辑失败，订单编号：{}", orderFormId, e);
        }
    }

    /**
     * 处理拼团订单
     */
    private void handleGroupWork(CereShopOrder order, String transactionId, String orderNo, String time) throws Exception {
        // 查询拼团活动数据
        CereCollageOrder collageOrder = cereCollageOrderService.findById(order.getShopGroupWorkId());
        if (collageOrder != null) {
            // 修改订单支付状态和订单状态
            order.setUpdateTime(time);
            order.setPaymentState(IntegerEnum.ORDER_PAY_SUCCESS.getCode());
            order.setPaymentTime(time);
            order.setState(IntegerEnum.ORDER_STAY_DILEVERY.getCode());
            cereShopOrderDAO.updateByPrimaryKeySelective(order);

            // 新增订单对账数据
            addReconciliation(order, time);
            // 新增支付流水数据
            addPayLog(order, time, orderNo, transactionId);

            // 删除自动关闭订单延时任务
            stringRedisService.delete(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId());
            // 删除延时任务记录
            cereRedisKeyServcice.deleteByKey(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId());

            log.info("拼团订单处理完成，订单ID：{}", order.getOrderId());
        }
    }

    /**
     * 处理秒杀订单
     */
    private void handleSeckill(CereShopOrder order, String transactionId, String orderNo, String time) throws Exception {
        // 查询秒杀活动数据
        CereShopSeckill cereShopSeckill = cereShopSeckillService.findById(order.getShopSeckillId());
        if (cereShopSeckill != null) {
            // 修改订单支付状态和订单状态
            order.setUpdateTime(time);
            order.setPaymentState(IntegerEnum.ORDER_PAY_SUCCESS.getCode());
            order.setPaymentTime(time);
            order.setState(IntegerEnum.ORDER_STAY_DILEVERY.getCode());
            cereShopOrderDAO.updateByPrimaryKeySelective(order);

            // 新增订单对账数据
            addReconciliation(order, time);
            // 新增支付流水数据
            addPayLog(order, time, orderNo, transactionId);

            // 删除自动关闭订单延时任务
            stringRedisService.delete(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId());
            // 删除延时任务记录
            cereRedisKeyServcice.deleteByKey(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId());

            log.info("秒杀订单处理完成，订单ID：{}", order.getOrderId());
        }
    }

    /**
     * 处理限时折扣订单
     */
    private void handleDiscount(CereShopOrder order, String transactionId, String orderNo, String time) throws Exception {
        // 查询限时折扣活动数据
        CereShopDiscount cereShopDiscount = cereShopDiscountService.findById(order.getShopDiscountId());
        if (cereShopDiscount != null) {
            // 修改订单支付状态和订单状态
            order.setUpdateTime(time);
            order.setPaymentState(IntegerEnum.ORDER_PAY_SUCCESS.getCode());
            order.setPaymentTime(time);
            order.setState(IntegerEnum.ORDER_STAY_DILEVERY.getCode());
            cereShopOrderDAO.updateByPrimaryKeySelective(order);

            // 新增订单对账数据
            addReconciliation(order, time);
            // 新增支付流水数据
            addPayLog(order, time, orderNo, transactionId);

            // 删除自动关闭订单延时任务
            stringRedisService.delete(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId());
            // 删除延时任务记录
            cereRedisKeyServcice.deleteByKey(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId());

            log.info("限时折扣订单处理完成，订单ID：{}", order.getOrderId());
        }
    }

    /**
     * 处理普通订单
     */
    private void handleOrder(CereShopOrder order, String transactionId, String orderNo, String time,
                             List<CereDistributionOrder> distributionOrders, List<CereShopConversion> conversions) throws Exception {
        // 修改订单支付状态和订单状态
        order.setUpdateTime(time);
        order.setPaymentState(IntegerEnum.ORDER_PAY_SUCCESS.getCode());
        order.setPaymentTime(time);
        order.setState(IntegerEnum.ORDER_STAY_DILEVERY.getCode());
        cereShopOrderDAO.updateByPrimaryKeySelective(order);

        // 新增订单对账数据
        addReconciliation(order, time);
        // 新增支付流水数据
        addPayLog(order, time, orderNo, transactionId);

        // 删除自动关闭订单延时任务
        stringRedisService.delete(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId());
        // 删除延时任务记录
        cereRedisKeyServcice.deleteByKey(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId());

        // 处理分销订单
        handleDistributionOrder(order, distributionOrders);

        // 处理转化数据
        handleConversionData(order, conversions);

        log.info("普通订单处理完成，订单ID：{}", order.getOrderId());
    }

    /**
     * 更新商品销量统计
     */
    private void updateProductSalesStats(List<Long> orderIdList) {
        try {
            List<CartSku> statsList = cereOrderProductService.findProductStatsByOrderIds(orderIdList);
            if (CollectionUtils.isNotEmpty(statsList)) {
                Map<Long, List<CartSku>> productOpMap = statsList.stream().collect(Collectors.groupingBy(CartSku::getProductId));

                // 更新日度统计
                for (Long productId : productOpMap.keySet()) {
                    List<CartSku> skuList = productOpMap.get(productId);
                    Long shopId = skuList.get(0).getShopId();
                    int number = skuList.stream().map(CartSku::getNumber).reduce((x, y) -> x += y).orElse(0);

                    CereProductStatsByDay stats = new CereProductStatsByDay();
                    stats.setShopId(shopId);
                    stats.setCreateDate(TimeUtils.today());
                    stats.setProductId(productId);
                    stats.setAddCartCount(0);
                    stats.setVisitCount(0);
                    stats.setSalesVolume(number);
                    cereProductStatsByDayDAO.insertOrUpdate(stats);
                }

                // 更新sku实时信息(销量)
                for (CartSku stat : statsList) {
                    cereSkuMemberRealInfoDAO.increSalesVolumeBy(stat.getSkuId(), stat.getNumber());
                }

                log.info("商品销量统计更新完成，订单数量：{}", orderIdList.size());
            }
        } catch (Exception e) {
            log.error("更新商品销量统计失败", e);
        }
    }

    /**
     * 处理优惠券核销
     */
    private void handleCouponWriteOff(Long platformCouponId, Long buyerUserId) {
        try {
            CereBuyerCoupon cereBuyerCoupon = cereBuyerCouponService.findLatestUsedCoupon(platformCouponId, buyerUserId);
            if (cereBuyerCoupon != null) {
                CerePlatformActivity activity = cerePlatformActivityService.findById(cereBuyerCoupon.getCouponId());
                CereBuyerUser user = cereBuyerUserService.selectByBuyerUserId(buyerUserId);

                if (activity.getSyncCard() != null
                        && IntegerEnum.YES.getCode().equals(activity.getSyncCard())
                        && StringUtils.isNotBlank(activity.getCardId())
                        && StringUtils.isNotBlank(cereBuyerCoupon.getCouponCode())) {
                    wxCardUtil.useMerchantCoupon(activity.getCardId(), user.getWechatOpenId(), cereBuyerCoupon.getCouponCode());
                }

                log.info("优惠券核销完成，优惠券ID：{}", platformCouponId);
            }
        } catch (Exception e) {
            log.error("处理优惠券核销失败，优惠券ID：{}", platformCouponId, e);
        }
    }

    /**
     * 更新用户成长值和积分
     */
    private void updateUserGrowthAndCredit(Long buyerUserId, BigDecimal total) {
        try {
            // 支付金额四舍五入
            total = total.setScale(0, BigDecimal.ROUND_UP);

            // 增加成长值
            cereBuyerUserService.updateGrowth(buyerUserId, total.intValue());

            // 增加积分(默认每下单1元，增加1积分)
            int creditOrderRate = 1;
            CerePlatformDict creditOrderRateDict = cerePlatformDictService.getByName(DictConstants.CREDIT_ORDER_RATE);
            CerePlatformDict switchDict = cerePlatformDictService.getByName(DictConstants.CREDIT_SWITCH);

            if (switchDict != null && StringUtils.isNotBlank(switchDict.getDictDescribe())
                    && IntegerEnum.YES.getCode().equals(Integer.parseInt(switchDict.getDictDescribe()))) {
                if (creditOrderRateDict != null) {
                    try {
                        creditOrderRate = Integer.parseInt(creditOrderRateDict.getDictDescribe());
                    } catch (Exception e) {
                        log.warn("credit_order_rate config abnormal");
                    }
                }
                cereBuyerUserService.increaseCredit(buyerUserId, creditOrderRate * total.intValue(), CreditOptTypeEnum.PLACE_ORDER);
            }

            log.info("用户成长值和积分更新完成，用户ID：{}，成长值：{}，积分：{}",
                    buyerUserId, total.intValue(), creditOrderRate * total.intValue());
        } catch (Exception e) {
            log.error("更新用户成长值和积分失败，用户ID：{}", buyerUserId, e);
        }
    }

    /**
     * 处理分销订单
     */
    private void handleDistributionOrder(CereShopOrder order, List<CereDistributionOrder> distributionOrders) {
        // TODO: 实现分销订单处理逻辑
        log.info("分销订单处理逻辑待实现，订单ID：{}", order.getOrderId());
    }

    /**
     * 处理转化数据
     */
    private void handleConversionData(CereShopOrder order, List<CereShopConversion> conversions) {
        // TODO: 实现转化数据处理逻辑
        log.info("转化数据处理逻辑待实现，订单ID：{}", order.getOrderId());
    }

    /**
     * 新增订单对账数据
     */
    private void addReconciliation(CereShopOrder order, String time) {
        // TODO: 实现订单对账数据新增逻辑
        log.info("订单对账数据新增逻辑待实现，订单ID：{}", order.getOrderId());
    }

    /**
     * 新增支付流水数据
     */
    private void addPayLog(CereShopOrder order, String time, String orderNo, String transactionId) {
        // TODO: 实现支付流水数据新增逻辑
        log.info("支付流水数据新增逻辑待实现，订单ID：{}", order.getOrderId());
    }

    /**
     * 根据订单类型和订单号查询订单
     */
    private Double findOrderAmount(Integer orderType, String orderNo, Long buyerUserId) {
        //查询红包订单金额
        if (Objects.equals(TransactionTypeEnum.RED_PACKET_PAY.getCode(), orderType)) {
            RedPacket redPacket = redPacketService.findByOrderNo(orderNo, buyerUserId);
            return redPacket.getTotalAmount().doubleValue();
        } else if (Objects.equals(TransactionTypeEnum.TRANSFER_ORDER_PAY.getCode(), orderType)) {
            QueryWrapper<TransferOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id",orderNo);
            TransferOrder order = transferOrderMapper.selectOne(queryWrapper);
            return order.getAmount().doubleValue();
        }
        return null;
    }
}
